<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      :visible.sync="visible"
    >
      <el-form
        :model="inputForm"
        ref="inputForm"
        v-loading="loading"
        :class="method === 'view' ? 'readonly' : ''"
        :disabled="method === 'view'"
        label-width="120px"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="发布人" prop="publisher.id" :rules="[]">
              <GridSelect
                title="选择发布人"
                labelName="nikeName"
                labelValue="id"
                :value="inputForm.publisher.id"
                :limit="1"
                @getValue="
                  (value) => {
                    inputForm.publisher.id = value;
                  }
                "
                :columns="[
                  {
                    prop: 'id',
                    label: '主键',
                  },
                  {
                    prop: 'phone',
                    label: '手机号(账号唯一)',
                  },
                  {
                    prop: 'nikeName',
                    label: '昵称',
                  },
                ]"
                :searchs="[
                  {
                    prop: 'phone',
                    label: '手机号(账号唯一)',
                  },
                ]"
                dataListUrl="/userinfo/tUserInfo/list"
                entityBeanName="tUserInfo"
                queryEntityUrl="/userinfo/tUserInfo/queryById"
              >
              </GridSelect>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="经销商" prop="store.id" :rules="[]">
              <GridSelect title="选择所属门店" labelName="storeName" labelValue="id" :value="inputForm.store.id" :limit="1"
                @getValue="
                  (value) => {
                    inputForm.store.id = value;
                  }
                " :columns="[
                  {
                    prop: 'storeName',
                    label: '门店名称',
                  },
                  {
                    prop: 'officeAddress',
                    label: '办公地址',
                  },
                  {
                    prop: 'storeContactNumber',
                    label: '门店联系电话',
                  },
                  {
                    prop: 'legalName',
                    label: '联系人',
                  },
                  {
                    prop: 'contactPhoneNumber',
                    label: '联系人电话',
                  },
                ]" :searchs="[
                  {
                    prop: 'storeName',
                    label: '门店名称',
                  },
                  {
                    prop: 'storeContactNumber',
                    label: '门店联系电话',
                  },
                ]" dataListUrl="/distributor/vDistributor/list" entityBeanName="vDistributor"
                queryEntityUrl="/distributor/vDistributor/queryById">
              </GridSelect>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="图片" prop="picture" :rules="[]">
              <el-upload
                ref="picture"
                v-if="visible"
                list-type="picture-card"
                :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/vhelpingfriendscircle/vHelpingFriendsCircle`"
                :headers="{ token: $cookie.get('token') }"
                :on-preview="
                  (file, fileList) => {
                    showImg(file.url);
                  }
                "
                :on-success="
                  (response, file, fileList) => {
                    inputForm.picture = fileList
                      .map(
                        (item) =>
                          (item.response && item.response.url) || item.url
                      )
                      .join('|');
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    $http
                      .post(
                        `/sys/file/webupload/deleteByUrl?url=${
                          (file.response && file.response.url) || file.url
                        }`
                      )
                      .then(({ data }) => {
                        $message.success(data.msg);
                      });
                    inputForm.picture = fileList
                      .map((item) => item.url)
                      .join('|');
                  }
                "
                :before-remove="
                  (file, fileList) => {
                    return $confirm(`确定移除 ${file.name}？`);
                  }
                "
                multiple
                :limit="5"
                :on-exceed="
                  (files, fileList) => {
                    $message.warning(
                      `当前限制选择 5 个文件，本次选择了 ${
                        files.length
                      } 个文件，共选择了 ${
                        files.length + fileList.length
                      } 个文件`
                    );
                  }
                "
                :file-list="pictureArra"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="视频" prop="video" :rules="[]">
              <el-upload
                ref="video"
                v-if="visible"
                :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/vhelpingfriendscircle/vHelpingFriendsCircle`"
                :headers="{ token: $cookie.get('token') }"
                :on-preview="
                  (file, fileList) => {
                    $window.location.href =
                      (file.response && file.response.url) || file.url;
                  }
                "
                :on-success="
                  (response, file, fileList) => {
                    inputForm.video = fileList
                      .map(
                        (item) =>
                          (item.response && item.response.url) || item.url
                      )
                      .join('|');
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    $http
                      .post(
                        `/sys/file/webupload/deleteByUrl?url=${
                          (file.response && file.response.url) || file.url
                        }`
                      )
                      .then(({ data }) => {
                        $message.success(data.msg);
                      });
                    inputForm.video = fileList
                      .map((item) => item.url)
                      .join('|');
                  }
                "
                :before-remove="
                  (file, fileList) => {
                    return $confirm(`确定移除 ${file.name}？`);
                  }
                "
                multiple
                :limit="5"
                :on-exceed="
                  (files, fileList) => {
                    $message.warning(
                      `当前限制选择 5 个文件，本次选择了 ${
                        files.length
                      } 个文件，共选择了 ${
                        files.length + fileList.length
                      } 个文件`
                    );
                  }
                "
                :file-list="videoArra"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">添加相关附件</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content" :rules="[]">
              <el-input
                type="textarea"
                v-model="inputForm.content"
                placeholder="请填写内容"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="浏览量" prop="views" :rules="[]">
              <el-input
                v-model="inputForm.views"
                placeholder="请填写浏览量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="详细地址"
              prop="detailedAddress"
              :rules="[
                {
                  required: true,
                  message: '店铺地址不能为空',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                type="text"
                id="handleinputs"
                ref="handleinputs"
                v-model="inputForm.detailedAddress"
                placeholder="请填写详细地址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="经度"
              prop="longitude"
              :rules="[
                { required: true, message: '经度不能为空', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="inputForm.longitude"
                placeholder="请填写经度"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="纬度"
              prop="latitude"
              :rules="[
                { required: true, message: '纬度不能为空', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="inputForm.latitude"
                placeholder="请填写纬度"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="地图" prop="">
              <div ref="container" id="containepic"></div>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item
              label="审核状态"
              prop="auditStatus"
              :rules="[
                 ]"
            >
              <el-select
                v-model="inputForm.auditStatus"
                placeholder="请选择"
                style="width: 100%;"
              >
                <el-option
                  label="待审核"
                  value="0"
                ></el-option>
                <el-option
                  label="已通过"
                  value="1"
                ></el-option>
                <el-option
                  label="已拒绝"
                  value="2"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks" :rules="[]">
              <el-input
                type="textarea"
                v-model="inputForm.remarks"
                placeholder="请填写备注信息"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <div v-show="active == 2" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item
                label="经度"
                prop="longitude"
                :rules="[
                  ]"
              >
                <el-input
                  v-model="inputForm.longitude"
                  placeholder="请填写经度"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="纬度"
                prop="latitude"
                :rules="[
                  ]"
              >
                <el-input
                  v-model="inputForm.latitude"
                  placeholder="请填写纬度"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" prop="detailedAddress" :rules="[]">
                <el-input
                  type="textarea"
                  id="handleinputs"
                  v-model="inputForm.detailedAddress"
                  placeholder="请填写详细地址"
                ></el-input>
              </el-form-item>
            </el-col>
          </div> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button
          type="primary"
          v-if="method != 'view'"
          @click="doSubmit()"
          v-noMoreClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GridSelect from "@/components/gridSelect";
export default {
  data() {
    return {
      title: "",
      method: "",
      visible: false,
      loading: false,
      pictureArra: [],
      videoArra: [],
      markersArray: [],
      inputForm: {
        id: "",
        publisher: {
          id: "",
        },
        store: {
          id: "",
        },
        picture: "",
        video: "",
        content: "",
        longitude: "",
        latitude: "",
        detailedAddress: "",
        views: "",
        auditStatus: "",
        remarks: "",
      },
    };
  },
  components: {
    GridSelect,
  },
  activated() {
    this.searchForm.auditStatus = this.$route.query.auditStatus;
    this.refreshList();
  },
  methods: {
    showImg(url) {
      this.$hevueImgPreview(url);
    },
    init(method, id) {
      this.method = method;
      this.inputForm.id = id;
      if (method === "add") {
        this.title = `新建帮友圈信息表`;
      } else if (method === "edit") {
        this.title = "修改帮友圈信息表";
      } else if (method === "view") {
        this.title = "查看帮友圈信息表";
      }
      this.pictureArra = [];
      this.videoArra = [];
      this.visible = true;
      this.loading = false;
      this.$nextTick(() => {
        this.$refs.inputForm.resetFields();
        if (method === "edit" || method === "view") {
          // 修改或者查看
          this.loading = true;
          this.$http({
            url: `/vhelpingfriendscircle/vHelpingFriendsCircle/queryById?id=${this.inputForm.id}`,
            method: "get",
          }).then(({ data }) => {
            this.inputForm = this.recover(
              this.inputForm,
              data.vHelpingFriendsCircle
            );
            this.initMap(this.inputForm.longitude, this.inputForm.latitude);
            this.inputForm.picture.split("|").forEach((item) => {
              if (item.trim().length > 0) {
                this.pictureArra.push({
                  name: decodeURIComponent(
                    item.substring(item.lastIndexOf("/") + 1)
                  ),
                  url: item,
                });
              }
            });
            this.inputForm.video.split("|").forEach((item) => {
              if (item.trim().length > 0) {
                this.videoArra.push({
                  name: decodeURIComponent(
                    item.substring(item.lastIndexOf("/") + 1)
                  ),
                  url: item,
                });
              }
            });
            this.loading = false;
          });
        } else {
          this.initMap();
        }
      });
    },
    initMap(longitude, latitude) {
      var that = this;
      let address = "";

      let lat = "36.752508224779746";
      let logt = "119.97121810913086";
      if (!longitude) {
        let lat = latitude;
        let logt = longitude;
      }
      if (this.inputForm.latitude === "") {
        var center = new qq.maps.LatLng(lat, logt);
      } else {
        var center = new qq.maps.LatLng(
          this.inputForm.latitude,
          this.inputForm.longitude
        );
      }
      var map = new qq.maps.Map(document.getElementById("containepic"), {
        center: center,
        zoom: 13,
        disableDefaultUI: true,
      });
      var marker = new qq.maps.Marker({
        position: center,
        map: map,
      });
      that.markersArray.push(marker);
      var infoWin = new qq.maps.InfoWindow({
        map: map,
      }); //此处是点击地图后生成的地标名称
      var geocoder = new qq.maps.Geocoder({
        complete: function (res) {
          console.log(res, 123);
          that.deleteOverlays();
          map.setCenter(res.detail.location);
          var marker = new qq.maps.Marker({
            map: map,
            position: res.detail.location,
          });
          that.markersArray.push(marker);
        },
      });

      qq.maps.event.addListener(map, "click", function (event) {
        that.deleteOverlays();
        this.latitude = event.latLng.getLat();
        this.longiistude = event.latLng.getLng();
        console.log(this.longiistude, this.latitude);
        that.inputForm.longitude = this.longiistude;
        that.inputForm.latitude = this.latitude;
        var position = new qq.maps.LatLng(
          that.inputForm.latitude,
          that.inputForm.longitude
        );
        var marker = new qq.maps.Marker({
          map: map,
          position: position,
        });
        that.markersArray.push(marker);
      });
      document
        .getElementById("handleinputs")
        .addEventListener("blur", function () {
          geocoder.getLocation(that.inputForm.detailedAddress);
        });
    },
    deleteOverlays() {
      if (this.markersArray) {
        for (var i in this.markersArray) {
          this.markersArray[i].setMap(null);
        }
        this.markersArray.length = 0;
      }
    },
    // 表单提交
    doSubmit() {
      this.$refs["inputForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$http({
            url: `/vhelpingfriendscircle/vHelpingFriendsCircle/save`,
            method: "post",
            data: this.inputForm,
          }).then(({ data }) => {
            this.loading = false;
            if (data && data.success) {
              this.visible = false;
              this.$message.success(data.msg);
              this.$emit("refreshDataList");
            }
          });
        }
      });
    },
  },
};
</script>
<style>
#containepic {
  width: 750px;
  height: 500px;
}
</style>
